package com.yu.controller;

import cn.hutool.core.util.StrUtil;
import com.yu.entity.User;
import com.yu.exception.BusinessException;
import com.yu.service.AdmainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admain")
public class AdmainController {
    @Autowired
    private AdmainService admainService;
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        if(StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            throw new BusinessException(Code.BUSINESS_ERR,"用户名或密码为空");
        }
        User one = admainService.selectOne(user);
        Integer code = one != null ? Code.GET_OK : Code.GET_ERR;
        String msg = one != null ? "登陆成功" : "登陆失败";
        return new Result(code,one,msg);
    }
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if(StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            throw new BusinessException(Code.BUSINESS_ERR,"用户名或密码为空");
        }
        Boolean flag = admainService.register(user);

        Integer code = flag ? Code.SAVE_OK : Code.SAVE_ERR;
        String msg = flag ? "注册成功" : "注册失败";
        return new Result(code,flag,msg);
    }
    @GetMapping()
    public Result selectAll() {
        List<User> users = admainService.selectAll();
        Integer code = users!=null ? Code.GET_OK : Code.GET_ERR;
        return new Result(code,users);
    }
    @PostMapping()
    public Result save(@RequestBody User user) {
        Boolean flag = admainService.save(user);
        Integer code = flag ? Code.SAVE_OK : Code.SAVE_ERR;
        return new Result(code,flag);
    }
    @DeleteMapping("/{id}")
    public Result deleteOne(@PathVariable Integer id) {
        Boolean flag = admainService.deleteOne(id);
        Integer code = flag ? Code.DELETE_OK : Code.DELETE_ERR;
        return new Result(code,flag);
    }
    @GetMapping("/{id}")
    private Result selectOneById(@PathVariable Integer id) {
        User user = admainService.selectOneById(id);
        Integer code = user!=null ? Code.GET_OK : Code.GET_ERR;
        return new Result(code,user);
    }
    @PutMapping
    public Result updateOne(@RequestBody User user) {
        Boolean flag = admainService.updateOne(user);
        String msg = flag ? "修改管理员信息成功" : "管理员信息修改失败，请重试！";
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR, flag, msg);
    }
}
